/**
 * 
 */
package com.hezhi.framework.dao.common;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Hou-jun.Fan <br/>
 */
class ArgSetter {

	private final Object[] args;

	private final Object[][] batchArgs;

	public ArgSetter(Object[] args) {
		this.args = new Object[args.length];
		System.arraycopy(args, 0, this.args, 0, args.length);

		this.batchArgs = null;
	}

	public ArgSetter(Object[][] batchArgs) {
		this.args = null;
		this.batchArgs = new Object[batchArgs.length][];
		for (int i = 0; i < batchArgs.length; i++){
			this.batchArgs[i] = new Object[batchArgs[i].length];
			System.arraycopy(batchArgs[i], 0, this.batchArgs[i], 0, batchArgs[i].length);
		}
	}

	public void setValues(PreparedStatement ps) throws SQLException {
		if (args != null) {
			int i = 1;
			for (Object arg : args) {
				doSetValue(ps, i++, arg);
			}
		}
	}

	public int getBatchSize() {
		if (batchArgs != null) {
			return batchArgs.length;
		} else {
			return 0;
		}
	}

	public void setValues(PreparedStatement ps, int index) throws SQLException {
		if (batchArgs != null) {
			if (batchArgs[index] != null) {
				int i = 1;
				for (Object arg : batchArgs[index]) {
					doSetValue(ps, i++, arg);
				}
			}
		}
	}

	private void doSetValue(PreparedStatement ps, int parameterPosition,
			Object argValue) throws SQLException {
		if (argValue == null) {
			ps.setObject(parameterPosition, null);
		} else {
			if (argValue instanceof String) {
				ps.setString(parameterPosition, argValue.toString());
			} else if (argValue instanceof Date) {
				ps.setTimestamp(parameterPosition, new java.sql.Timestamp(
						((Date) argValue).getTime()));
			} else if (argValue instanceof Calendar) {
				Calendar cal = (Calendar) argValue;
				ps.setTimestamp(parameterPosition, new java.sql.Timestamp(cal
						.getTime().getTime()));
			} else {
				ps.setObject(parameterPosition, argValue);
			}
		}
	}
}
